<!--
 * @Author: guo wei
 * @LastEditors: [guo wei]
 * @LastEditTime: 2024-03-17 21:31:19
 * @Description: 
-->
<template>
  <div class="report-wrap" @click="resetCanvas">
    <div class="report-header">
      <el-page-header :icon="House" @back="goBack">
        <template #content>
          <div class="page-content">
            <span v-if="isEditTitle" class="page-title font-600">
              {{ pageTitle }}
            </span>
            <el-input v-else v-model="pageTitle" placeholder="请输入" />
            <el-button @click="isEditTitle = !isEditTitle" style="margin-left: 15px" link :icon="EditPen" />
          </div>
        </template>
      </el-page-header>
      <div class="right-header-content">
        <el-button type="primary" @click="submitSaveByBtn">保存</el-button>
        <el-button @click="dialogVisible = true">建筑类型</el-button>
        <el-button type="primary">材料匹配</el-button>
        <el-dropdown @command="handleCommand">
          <el-button><el-icon class="el-icon--right">
              <More />
            </el-icon></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="a">返回上一步</el-dropdown-item>
              <el-dropdown-item command="b">导出PPT</el-dropdown-item>
              <!-- <el-dropdown-item command="c">导出PDF</el-dropdown-item> -->
              <el-dropdown-item command="d">另存为</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-avatar :size="30" :src="circleUrl" />
      </div>
    </div>
    <div class="report-content">
      <div class="report-box">
        <div class="report-ppt-item item-first">
          <img class="first-banner" src="@/assets/images/ppt-banner.png" alt="" />
          <div class="item-first-bottom">
            <div class="first-item-title">{{ pageTitle }}</div>
            <div class="item-date">{{ new Date() }}</div>
          </div>
        </div>
        <div class="report-ppt-item item-second">
          <div class="page-title">{{ pageTitle }}</div>
          <div class="brand-title">目录</div>
          <div class="ppt-title">1.立面效果图</div>
          <div class="ppt-title">2.典型单体彩色立面索引</div>
          <div class="ppt-title">3.材料篇</div>
          <div class="ppt-title">4.节点篇</div>
          <div class="page-footer-title">立面控制手册</div>
        </div>
        <div class="report-ppt-item item-third">
          <div class="page-title">1.立面效果图</div>
        </div>
        <div class="report-ppt-item item-forth"></div>
        <div class="report-ppt-item item-fifth">
          <div class="page-title">2.典型单体彩色立面索引</div>
        </div>
        <ModelMap :modelId="modelInfoId" :colorType="true" @getSceneLength="getSceneLength" @getImgData="getImgData"
          :top="canvasTop" :activeCanvas="activeCanvas" :left="canvasLeft" :isEdit="isEdit"
          @getMaterialData="getMaterialData">
        </ModelMap>
        <div class="report-ppt-item item-sixth fif" v-for="(item, index) in cameraImgData" :key="item">
          <div class="page-title">立面分色图</div>
          <div class="container" :id="'container_' + index">
            <el-button :icon="More" size="small" v-if="!item.isEdit" @click.stop="editCanvas(item, index)"
              class="edit-btn">
            </el-button>
            <div class="operate-btn-wrap" v-if="item.isEdit">
              <el-button :icon="Close" size="small" @click.stop="cancelCanvas(item, index)" class="oprate-btn">
              </el-button>
              <el-button :icon="Check" size="small" @click.stop="confirmCanvas(item, index)" class="oprate-btn">
              </el-button>
            </div>
            <div class="canvas-wrap">
              <div style="flex: 1" ref="canvasRef">
                <img :src="item.url" style="width: 420px" alt="" v-if="!item.isEdit" />
                {{ item.name }}{{ item.colorType }}
              </div>
            </div>
            <div class="table-wrap">
              <el-table max-height="460" :data="cameraTableData" style="margin-right: 15px; flex: 1">
                <el-table-column label="操作" width="100">
                  <template #header>
                    <el-button type="primary" @click="matchTable" size="mini">
                      匹配
                    </el-button>
                  </template>
                  <template #default="scope">
                    <el-button link type="primary" size="mini" @click.prevent="deleteRow(scope.row.id)">
                      <el-icon>
                        <Remove />
                      </el-icon>
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="color" label="配色" width="60">
                  <template #default="scope">
                    <div class="color-badge" :style="{ background: scope.row.color || '' }"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="userPart" label="使用部位" width="150">
                  <template #default="scope">
                    <el-autocomplete v-model="scope.row.userPart" :fetch-suggestions="querySearchUserPart"
                      class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                      @select="handleSelect" />
                  </template>
                </el-table-column>
                <el-table-column prop="material" label="材料名">
                  <template #default="scope">
                    <el-autocomplete v-model="scope.row.material" :fetch-suggestions="querySearchMaterial"
                      class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                      @select="handleSelect" />
                  </template>
                </el-table-column>
              </el-table>
              <el-button class="mt-4" style="width: 100%" @click="onAddItem(item)">
                新增
              </el-button>
            </div>
          </div>
          <!-- <img :src="item" style="width: 500px; height: 300px" alt="" /> @change="(data) => changeUserPart(data, scope.row)"-->
        </div>
        <div class="report-ppt-item item-seventh">
          <div class="page-title">材料篇</div>
          <div class="page-bottom-desc">
            i.材料篇（包含各部位外立面材料编号、部位、材料、颜色、加工工艺、参考图片、节点详图、及材料厂家信息等相关必要信息）
          </div>
        </div>
        <div class="report-ppt-item item-eighth">
          <div class="page-header">
            <div class="page-title">立面材料表</div>
            <el-button type="primary" :disabled="cameraTableData.length == 0" @click="matchByGreyTableFirst">
              智能匹配
            </el-button>
          </div>
          <el-table @row-click="tableFirstRowClick" :data="tableData" border style="width: 100%">
            <el-table-column label="材料编号">
              <template #default="scope">
                <el-input class="inline-input w-50" @focus.stop @click.stop v-model="scope.row.code"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="userPart" label="部位">
            </el-table-column>
            <el-table-column prop="materialName" label="材料">
            </el-table-column>
            <el-table-column prop="color" label="颜色">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.color"
                  :fetch-suggestions="(queryString, cb) => querySearchColorList(queryString, cb, scope.row.colorList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
            <el-table-column prop="technology" label="加工工艺">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.technology"
                  :fetch-suggestions="(queryString, cb) => querySearchTechnologyList(queryString, cb, scope.row.technologyList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
            <el-table-column prop="img" label="参考图片">
              <template #default="scope">
                <!--upload-->
                <el-upload @click.stop class="avatar-uploader" :action="'http://8' + '/image/image'"
                  list-type="picture-card" :show-file-list="false" :on-success="getDataSrc">
                  <img v-if="scope.row.coverPage" :src="scope.row.coverPage" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column prop="caseImg" label="案例图片">
              <template #default="scope">
                <el-upload @click.stop class="avatar-uploader" :action="'http://8' + '/image/image'"
                  list-type="picture-card" :show-file-list="false" :on-success="getDataSrc">
                  <img v-if="scope.row.caseImg" :src="scope.row.caseImg" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="report-ppt-item item-eighth">
          <div class="page-header">
            <div class="page-title">材料信息表</div>
            <el-button type="primary" :disabled="cameraTableData.length == 0" @click="matchByGreyTable">
              智能匹配
            </el-button>
          </div>
          <el-table :data="materialTableData" border style="width: 100%">
            <el-table-column prop="materialName" label="材料">
            </el-table-column>
            <el-table-column prop="img" label="参考图片">
              <template #default="scope">
                <!--upload-->
                <el-upload class="avatar-uploader" :action="'http://8' + '/image/image'" list-type="picture-card"
                  :show-file-list="false" :on-success="getDataSrc">
                  <img v-if="scope.row.coverPage" :src="scope.row.coverPage" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="品牌">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.brand"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.brandList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.specifications"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.specificationsList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
            <el-table-column prop="model" label="型号">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.model"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.modelList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
            <el-table-column prop="address" label="产地">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.producer"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.producerList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template> </el-table-column>
            <el-table-column prop="price" label="价格">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.price"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.priceList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template> </el-table-column>
            <el-table-column prop="materialSupplierInfoId" label="材料厂家信息">
              <template #default="scope">
                <el-autocomplete v-model="scope.row.materialSupplierInfoId"
                  :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb, scope.row.materialSupplierInfoIdList)"
                  class="inline-input w-50" placeholder="请输入" @focus.stop @click.stop @change.stop
                  @select="handleSelect" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="report-ppt-item item-seventh">
          <div class="page-title">节点篇</div>
          <div class="page-bottom-desc">
            i.节点篇（包含各部位外立面主要节点的局部透视彩图、节点详图）
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="请确认建筑类型" width="30%">

      <el-form label-width="120px" :model="formInline" class="demo-form-inline">
        <el-form-item label="建筑类型">
          <el-cascader v-model="formInline.building" :options="buildingData" :props="cascaderProps" />
        </el-form-item>
        <el-form-item label="色系">
          <el-select v-model="formInline.colorSys" @change="changeColorSys" placeholder="选择色系" clearable>
            <el-option v-for="item in colorSysOptions" :key="item.colorSystemInfoId" :label="item.colorSystemName"
              :value="item.colorSystemInfoId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="颜色">
          <el-select multiple v-model="formInline.color" placeholder="选择颜色">
            <el-option v-for="item in colorInfoOptions" :key="item.colorInfoId" :label="item.colorName"
              :value="item.colorInfoId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="档次">
          <el-radio-group v-model="formInline.grade">
            <el-radio-button v-for="item in gradeInfoOptions" :key="item.gradeInfoId" :label="item.gradeName" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <div class="drawer-wrap" v-if="drawer">
      <h2>材料表</h2>
      <el-table @row-click="drawerRowClick" :data="materialTableData" border style="width: 100%">
        <el-table-column prop="materialName" label="材料名"> </el-table-column>
        <el-table-column label="价格区间">
          <template #default="scope">
            {{ scope.row.priceMin }} -- {{ scope.row.priceMax }}
          </template>
        </el-table-column>
        <el-table-column label="封面">
          <template #default="scope">
            <img style="height: 100px" :src="publicUrl + scope.row.coverPage" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="贴图">
          <template #default="scope">
            <img style="height: 100px" :src="publicUrl + scope.row.suBlock" alt="" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, watch, onMounted, onBeforeMount, nextTick, provide } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { House, EditPen, More, Close, Check, Remove } from "@element-plus/icons-vue";
import ModelMap from "../viewer/index.vue";
import cache from "@/plugins/cache";
import { useRouter } from 'vue-router'
import Pptxgen from "pptxgenjs"
import { allBuildingTypeInfo } from "@/api/building-type.js";
import {
  getMaterialInfo,
  getMaterialDetailInfo,
  getUsedPartInfos,
  getMaterialInfos,
  getCommodityIntelligentMatch,
  getCommodityIntelligentList,
  getPptInfoDetail,
  getModelInfoDetailData,
  addPptInfoDetail,
  modifyPptInfoDetail,
  getInfoSysSelectData,
  getColorInfoSelectData,
  getGradeInfoSelectData,
  addModelInfoData,
  modifyModelInfoData, getFacadeMaterialsMatch
} from "@/api/model";
const pageTitle = ref("成都万科天空之城");
const isEditTitle = ref(true);
const dialogVisible = ref(false);
const publicUrl = ref(cache.session.getJSON("publicUrl") || "");
const isEdit = ref(true);
const drawer = ref(false);
const cameraImgData = ref([]);
const cameraTableData = ref([]);
const circleUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);

const router = useRouter()
const modelId = ref('')
const modelInfoId = ref('')
const pptId = ref('')
const pptInfo = reactive({
  pptName: '',
  pptData: '',
  modelInfoId: '',
  recordVersion: ''
})

const onAddItem = (item) => {
  if (item.isEdit) {
    return ElMessage({
      message: "请点击左侧选择使用部位",
      type: "warning",
      duration: 5000,
    });
  }
  ElMessage({
    message: "请先编辑当前立面图，再选择新增使用部位",
    type: "warning",
    duration: 5000,
  });
}
const getModelInfo = async (id) => {
  const res = await getModelInfoDetailData(id)
  if (res.code == 200) {
    modelInfoId.value = res.result.elevation || ''
    if (modelInfoId.value == '') {
      loadingInstance.close();
      ElMessage({
        message: "暂无模型",
        type: "warning",
      });
    }
    formInline.building = res.result.buildingTypeName.split(",").map(x => Number(x)) || []
    formInline.colorSys = Number(res.result.colorSystemValue) || ''
    formInline.grade = res.result.gradeName || ''
  }
}
const goBack = () => {
  console.log('go back');
  router.push('/list/model-list')
}
const deleteRow = (id) => {
  const index = cameraTableData.value.findIndex(item => item.id == id)
  cameraTableData.value.splice(index, 1)
}
const modifyType = ref("edit")
// 监听当前路由
watch(
  () => router.currentRoute.value,
  (newValue) => {
    console.log('newValue', newValue)
    if (!newValue.query) return
    modelId.value = newValue.query.modelId
    pptId.value = newValue.query.pptInfoId
    getModelInfo(modelId.value)
    if (!newValue.query.pptInfoId) return
    getPptInfoDetail(newValue.query.pptInfoId).then((res) => {
      if (res.code == 200) {
        if (res.result.modelStatus == '0') {
          modifyType.value = 'edit'
          // 如果未上传
        } else {
          cameraTableData.value = res.result.pptFacadeMaterialsInfoVOS ? res.result.pptFacadeMaterialsInfoVOS.map(x => {
            return {
              id: x.materialInfoId,
              color: '--',
              userPart: x.usedPartName,
              material: x.materialName
            }
          }) : []
          tableData.value = res.result.pptFacadeMaterialsInfoVOS ? res.result.pptFacadeMaterialsInfoVOS.map(x => {
            return {
              ...x,
              code: x.materialCode,
              userPart: x.usedPartName,
              materialName: x.materialName,
              color: x.colorName,
              technology: x.technology,
              img: x.coverPage,
              caseImg: x.exampleUrl
            }
          }) : []
          // if (tableData.value.length > 0) {
          //   matchByGreyTableFirst()
          // }
          materialTableData.value = res.result.pptMaterialInfoVOS ? res.result.pptMaterialInfoVOS.map(x => {
            return {
              ...x,
              materialName: x.materialName,
              coverPage: x.exampleUrl,
              brand: x.brand,
              specifications: x.specifications,
              model: x.model,
              producer: x.producer,
              price: x.price,
              materialSupplierInfoId: x.materialSupplierInfoId
            }
          }) : []
          // if (materialTableData.value.length > 0) {
          //   matchByGreyTable()
          // }
        }
        pptInfo.pptName = res.result.pptName
        pptInfo.pptData = res.result.pptData
        pptInfo.modelInfoId = res.result.modelInfoId
        pptInfo.recordVersion = res.result.recordVersion
        pptInfo.pptInfoId = res.result.pptInfoId
      }
    });
  },
  { immediate: true }
)
const matchTable = async () => {
  cameraTableData.value.forEach(async (item) => {
    const res = await getFacadeMaterialsMatch({ usedPartInfoName: item.userPart })
    if (res.code == 200) {
      if (res.result.length > 0) {
        item.materialName = res.result[0].materialName
        ElMessage({
          message: "匹配成功",
          type: "success",
        });
      }
    }
  })
}
const submitSaveByBtn = () => {
  if (!pptId.value) {
    submitSave('add')
  } else {
    submitSave('edit')
  }
}
const submitSave = async (type) => {
  const pptFacadeMaterialsInfoDTOSTable = tableData.value.map(x => {
    return {
      ...x,
      colorName: x.color,
      coverPage: x.coverPage,
      exampleUrl: x.caseImg,
      materialCode: x.code,
      pptFacadeMaterialsInfoId: x.pptFacadeMaterialsInfoId || '',
      materialInfoId: x.materialInfoId,
      materialName: x.materialName,
      pptInfoId: pptId.value,
      technology: x.technology,
      usedPartName: x.userPart
    }
  })
  const pptMaterialInfoDTOSTable = materialTableData.value.map(x => {
    return {
      ...x,
      brand: x.brand,
      commodityInfoId: x.commodityInfoId,
      commodityName: x.commodityName,
      exampleUrl: x.exampleUrl,
      materialSupplierInfoId: x.materialSupplierInfoId || '',
      model: x.model,
      pptInfoId: pptId.value,
      price: x.price,
      producer: x.producer,
      specifications: x.specifications
    }
  })
  const pptInfos = {
    pptName: pptInfo.pptName,
    pptData: pptInfo.pptData,
    modelInfoId: pptInfo.modelInfoId,
    pptInfoId: pptInfo.pptInfoId,
    recordVersion: pptInfo.recordVersion,
    buildingTypeName: formInline.building.join(','),
    colorSystemValue: formInline.colorSys,
    gradeName: formInline.grade,
    pptFacadeMaterialsInfoDTOS: pptFacadeMaterialsInfoDTOSTable,
    pptMaterialInfoDTOS: pptMaterialInfoDTOSTable
  }
  if (type == 'edit') {
    const res = await modifyPptInfoDetail(pptInfos)
    if (res.code == 200) {
      ElMessage.success('操作成功')
      router.push('/list/model-list')
    } else {
      ElMessage.error('操作失败')
    }
  } else {
    const res = await addPptInfoDetail({ ...pptInfos, recordVersion: '' })
    if (res.code == 200) {
      ElMessage.success('操作成功')
      router.push('/list/model-list')
    } else {
      ElMessage.error('操作失败')
    }
  }

}

const loadingInstance = ElLoading.service({ fullscreen: true });
const sceneLength = ref(1);
const getSceneLength = (length) => {
  sceneLength.value = length;
};

const handleCommand = (cmd) => {
  switch (cmd) {
    case 'a':
      router.push('/list/model-list')
      break;
    case 'b':
      exportPPT()
      break;
    case 'd':
      submitSave('add')
      break;
    default:
      break;
  }
}

const exportPPT = async () => {

  // 1. 创建PPT
  const pres = new Pptxgen()

  // 2. 创建一个PPT页面，每调用一次 pres.addSlide() 都可以生成一张新的页面
  // 建议把每个页面的构造抽成一个个函数，然后通过函数调用生成新页面，代码不会很乱
  const slide = pres.addSlide()

  // 3. 调用addTetx()，在PPT页面中插入文字“Hello World from PptxGenJS...”
  // 括号里面是对文字的配置，文字横坐标x为1.5，纵坐标y为1.5，字体颜色 363636……
  // 关于坐标长度与px的转换 x 1 = 127~128px 左右
  slide.addImage({
    path: 'ppt-banner.png',  // 图片的路径  
    x: 0, y: '0',                   // 图片的位置（基于幻灯片的宽度和高度）  
    w: '100%', h: '80%'                 // 图片的宽度和高度（相对于幻灯片的大小）  
  });
  slide.addText(pageTitle.value, {
    x: 0, // 横坐标
    y: '85%',
    color: '363636',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide.addText(new Date().toLocaleDateString(), {
    x: 0, // 横坐标
    y: '95%',
    color: '363636',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  const slide2 = pres.addSlide()
  slide2.addText(pageTitle.value, {
    x: '30', // 横坐标
    w: '100%',
    y: '30',
    color: '363636',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'right'
  })
  slide2.addText('目录', {
    x: '15%', // 横坐标
    w: '100%',
    y: '15%',
    color: 'cac226',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide2.addText('1.立面效果图', {
    x: '15%', // 横坐标
    w: '100%',
    y: '25%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide2.addText('2.典型单体彩色立面索引', {
    x: '15%', // 横坐标
    w: '100%',
    y: '45%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide2.addText('3.材料篇', {
    x: '15%', // 横坐标
    w: '100%',
    y: '65%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide2.addText('4.节点篇', {
    x: '15%', // 横坐标
    w: '100%',
    y: '85%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left'
  })
  slide2.addText('立面控制手册', {
    x: '30', // 横坐标
    w: '100%',
    y: '90%',
    color: 'cac226',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'right'
  })
  const slide3 = pres.addSlide()
  slide3.addText('1.立面效果图', {
    x: '0', // 横坐标
    w: '100%',
    y: '45%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'center',
    vertical: 'middle'
  })
  const slide4 = pres.addSlide()
  slide4.addText(pageTitle.value, {
    x: '30', // 横坐标
    w: '100%',
    y: '30',
    color: '363636',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'right'
  })
  slide4.addText('立面控制手册', {
    x: '30', // 横坐标
    w: '100%',
    y: '90%',
    color: 'cac226',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'right'
  })
  const slide5 = pres.addSlide()
  slide5.addText('2.典型单体彩色立面索引', {
    x: '0', // 横坐标
    w: '100%',
    y: '45%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'center',
    vertical: 'middle'
  })
  if (cameraImgData.value.length > 0) {
    cameraImgData.value.forEach((item, index) => {
      const slidesNum = pres.addSlide()
      slidesNum.addText('立面分色图', {
        x: '20', // 横坐标
        w: '100%',
        y: '5%',
        color: 'ba6b10',
        fontSize: 14, // 字号
        fill: { color: 'F1F1F1' },
        align: 'left',
      })
      // const url = item.url
      slidesNum.addImage({
        data: item.url,  // 图片的路径  
        x: 0, y: '30%',                   // 图片的位置（基于幻灯片的宽度和高度）  
        w: '50%', h: '60%'                 // 图片的宽度和高度（相对于幻灯片的大小）  
      });
      const rows = []

      // Row One: cells will be formatted according to any options provided to `addTable()`
      rows.push(['使用部位', '材料名'])
      const border = [ // 表格边框
        { pt: 0.5, color: '#4f4f4f' },
        { type: 'none' },
        { pt: 0.5, color: '#4f4f4f' },
        { type: 'none' }
      ]
      const options = { valign: 'middle', border: border, color: '0000ff' }	// 单元格样式配置
      // Row Two: set/override formatting for each cell
      // for (let i in cameraImgData.value) {
      //   rows.push([{ text: cameraImgData.value[i].userPart, options },
      //   { text: cameraImgData.value[i].material, options }])
      // }
      console.log("cameraTableData.value", cameraTableData.value)
      if (cameraTableData.value.length > 0) {
        console.log("cameraTableData.value", cameraTableData.value)
        for (let i in cameraTableData.value) {
          rows.push([{ text: cameraTableData.value[i].userPart, options },
          { text: cameraTableData.value[i].material, options }])
        }
        console.log("cameraImgData", item, rows)
        slidesNum.addTable(rows,
          {
            x: '50%',
            y: '0',
            w: '50%',
            h: '80%',
            fontSize: 16,
            // colW: [0.75, 2.0, 0.85, 0.8], // 表格每一列宽度
            rowH: 0.31, // 单元格默认高度
            color: '363636'
          }
        )
      }

    })
  }
  const slidesLast = pres.addSlide()
  slidesLast.addText('节点篇', {
    x: '0', // 横坐标
    w: '100%',
    y: '45%',
    color: 'ba6b10',
    fontSize: 24, // 字号
    fill: { color: 'F1F1F1' },
    align: 'center',
    vertical: 'middle'
  })
  slidesLast.addText('i.节点篇（包含各部位外立面主要节点的局部透视彩图、节点详图）', {
    x: '0', // 横坐标
    w: '100%',
    y: '95%',
    color: 'ba6b10',
    fontSize: 14, // 字号
    fill: { color: 'F1F1F1' },
    align: 'left',
    vertical: 'middle'
  })
  pres.author = '作者_abin'

  pres.company = '公司'
  // 4. 生成PPT， 括号中的fileName，就是生成的 PPT名字，可以使用 .then 或者 .catch处理对应事件。
  pres.writeFile({ fileName: `${pptInfo.pptName}.pptx` }).then(() => {
    ElMessage.success('导出成功')
  })


}
const getImgData = (data) => {
  cameraImgData.value = data.map((x) => {
    return { ...x, isEdit: false };
  });
  if (data) {
    loadingInstance.close();
  }
};
function offsetTop(elements) {
  var top = elements.offsetTop;
  var parent = elements.offsetParent;
  while (parent != null) {
    top += parent.offsetTop;
    parent = parent.offsetParent;
  }
  // console.log(top);
  return top;
}
function offsetLeft(elements) {
  var left = elements.offsetLeft;
  var parent = elements.offsetParent;
  while (parent != null) {
    left += parent.offsetLeft;
    parent = parent.offsetParent;
  }

  return left;
}
const canvasTop = ref(-1000);
const activeCanvas = ref(-1);
const canvasLeft = ref(0);
const canvasRef = ref([]);
const editCanvas = (item, index) => {
  // const editArr = cameraImgData.value.filter((x) => x.isEdit == true);
  // if (editArr.length > 0) {
  //   return ElMessage({
  //     message: "当前有正在编辑的建筑，请确认后再操作",
  //     type: "warning",
  //   });
  // }
  activeCanvas.value = index;
  cameraImgData.value = cameraImgData.value.map((x, idx) => {
    if (idx == index) {
      return { ...x, isEdit: true };
    }
    return { ...x, isEdit: false };
  });
  // item.isEdit = true;
  canvasTop.value = offsetTop(
    document.getElementById("container_" + index).children[1].children[0]
  );
  canvasLeft.value = offsetLeft(
    document.getElementById("container_" + index).children[1].children[0]
  );
};
const resetCanvas = () => {
  // cameraImgData.value = cameraImgData.value.map((x) => {
  //   return { ...x, isEdit: false };
  // });
  drawer.value = false
};
const cancelCanvas = (item, index) => {
  item.isEdit = false;
  canvasTop.value = "-10000";
};
const confirmCanvas = (item, index) => {
  item.isEdit = false;
  canvasTop.value = "-10000";
  console.log("cameraTableData.value", cameraTableData.value);
};
const getMaterialData = (obj) => {
  console.log("getMaterialData", obj);
  const temp = cameraTableData.value.filter((x) => x.color == obj.color);
  if (temp.length > 0) {
    return ElMessage({
      message: "材料已存在，请重新操作！",
      type: "warning",
    });
  }
  let uniqueId = new Date().getTime();
  cameraTableData.value.unshift({ ...obj, userPart: "", id: uniqueId });
};

const tableData = ref([]);

const materialTableData = ref([]);



const matchByGreyTable = async () => {
  // ElMessageBox.confirm(
  //   "将基于立面分色图/材料图匹配对应材料信息，请确认立面分色图/材料图信息是否正确?",
  //   "提示",
  //   {
  //     confirmButtonText: "继续匹配",
  //     cancelButtonText: "取消",
  //     type: "warning",
  //   }
  // )
  //   .then(async () => {
  const materialNames = cameraTableData.value.map(
    (x) => x.material
  );
  try {

  } catch (error) {

  }
  const res = await getCommodityIntelligentMatch({ materialNames });
  const data = res.result
  console.log("getCommodityIntelligentMatch", res, cameraTableData.value);
  if (data.length > 0) {
    const publicFileUrl = cache.session.getJSON("publicUrl") || "";
    const temp =
      cameraTableData.value.map(async (x, idx) => {
        const exampleUrl = data[idx].exampleUrl ? publicFileUrl + data[idx].exampleUrl : ''
        const paramRes = await getCommodityIntelligentList({ count: false, materialName: data[idx].materialName })
        if (paramRes.code === 200) {
          const list = paramRes.result.list
          const brandList = list.length > 0 ? list.map(x => x.brand).filter(item => item !== undefined && item !== null && item !== '') : []
          const specificationsList = list.length > 0 ? list.map(x => x.specifications).filter(item => item !== undefined && item !== null && item !== '') : []
          const modelList = list.length > 0 ? list.map(x => x.model).filter(item => item !== undefined && item !== null && item !== '') : []
          const producerList = list.length > 0 ? list.map(x => x.producer).filter(item => item !== undefined && item !== null && item !== '') : []
          const priceList = list.length > 0 ? list.map(x => x.price).filter(item => item !== undefined && item !== null && item !== '') : []
          const materialSupplierInfoIdList = list.length > 0 ? list.map(x => x.materialSupplierInfoId).filter(item => item !== undefined && item !== null && item !== '') : []
          return {
            commodityInfoId: x.commodityInfoId,
            commodityName: x.commodityName,
            materialName: data[idx].materialName,
            exampleUrl: exampleUrl,
            brand: data[idx].brand,
            brandList: brandList,
            specifications: data[idx].specifications,
            specificationsList,
            model: data[idx].model,
            modelList,
            producer: data[idx].producer,
            producerList,
            price: data[idx].price,
            priceList,
            materialSupplierInfoId: data[idx].materialSupplierInfoId,
            materialSupplierInfoIdList,
          };
        }

      }) || [];
    materialTableData.value = await Promise.all(temp)
  } else {
    ElMessage({
      type: "warning",
      message: "暂无数据",
    });
  }
};


const currentFirstTableIndex = ref();
// cellClickAction方法,使用event判断当前节点类型，event具体内容可自行打印查看
function tableFirstRowClick(row, column, event) {
  event.stopPropagation()
  console.log("tableFirstRowClick", row);
  drawer.value = true;
  // const id = row.userPart.splice(-1);
  currentFirstTableIndex.value = row.userPart;
  console.log("tableFirstRowClick", currentFirstTableIndex.value);
  // getAllMaterialTableData(id);
}
function drawerRowClick(row, column, event) {
  drawer.value = false;
  tableData.value = tableData.value.map((x) => {
    if (x.userPart == row.userPart) {
      return { ...row, userPart: x.userPart, code: x.code };
    }
    return { ...x };
  });
  console.log("row", tableData.value);
}



const userPart = ref([]);
const getAllPartListData = async () => {
  try {
    const res = await getUsedPartInfos({ count: false });
    console.log("getAllPartListData", res);
    if (res.code === 200) {
      userPart.value = res.result.list || []
    }
  } catch (error) {

  }
};
getAllPartListData();


const colorDatas = ref([]);
const getMaterialDetailInfos = async () => {
  try {
    const materialNames = cameraTableData.value.map(
      (x) => x.material
    );
    const res = await getMaterialInfos({ count: false, materialName: materialNames });
    console.log("getMaterialDetailInfosss", res);
    if (res.code === 200) {
      colorDatas.value = res.result.list.map(x => x.materialColorInfoVOS) || []
    }
  } catch (error) {

  }
};
getMaterialDetailInfos();
/**
 * 自动补全输入框-颜色列表
 */
const querySearchColorList = (queryString, cb, data) => {
  const list = data.map(x => {
    return { value: x.colorName ? x.colorName : '' }
  })
  const results = queryString
    ? list.filter(createFilter(queryString))
    : list
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
    )
  }
}

const querySearchUserPart = (queryString, cb) => {
  const list = userPart.value.map(x => {
    return { value: x.usedPartName ? x.usedPartName : '' }
  })
  const results = queryString
    ? list.filter(createFilter(queryString))
    : list
  // call callback function to return suggestions
  cb(results)
}

const materialListDatas = ref([]);
const getMaterialSelectListData = async () => {
  const res = await getMaterialInfo();
  materialListDatas.value = res.result || []
  console.log("getMaterialSelectListData", res);
};
getMaterialSelectListData();

const querySearchMaterial = (queryString, cb) => {
  const list = materialListDatas.value.map(x => {
    return { value: x.materialName ? x.materialName : '' }
  })
  const results = queryString
    ? list.filter(createFilter(queryString))
    : list
  // call callback function to return suggestions
  cb(results)
}

/**
 * 自动补全输入框-工艺列表
 */
const querySearchTechnologyList = (queryString, cb, data) => {
  const list = data.map(x => {
    return { value: x ? x : '' }
  })
  const results = queryString
    ? list.filter(createFilter(queryString))
    : list
  console.log("querySearchTechnologyList", results)
  // call callback function to return suggestions
  cb(results)
}
/**
 * 材料信息表-自动补全输入框
 */
const querySearch = (queryString, cb, data) => {
  const list = data.map(x => {
    return { value: x ? x.toString() : '' }
  })
  const results = queryString
    ? list.filter(createQuerySearchFilter(queryString))
    : list
  console.log("querySearch", results)
  // call callback function to return suggestions
  cb(results)
}
const createQuerySearchFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
    )
  }
}
const matchByGreyTableFirst = async () => {

  // if (cameraTableData.value.length == 0) {
  //   return ElMessage({
  //     type: "warning",
  //     message: "暂无数据",
  //   });
  // }

  const materialNames = cameraTableData.value.map(
    (x) => x.material
  );
  try {
    const res = await getMaterialDetailInfo({ materialNames });
    const data = res.result
    if (data.length > 0) {
      const publicFileUrl = cache.session.getJSON("publicUrl") || "";
      const temp =
        cameraTableData.value.map(async (x, idx) => {
          const color = (data[idx].materialColorInfoVOS && data[idx].materialColorInfoVOS.length > 0) ? data[idx].materialColorInfoVOS[0].colorName : ''
          const caseImg = (data[idx].materialExampleVOS && data[idx].materialExampleVOS.length > 0) ? data[idx].materialExampleVOS[0].exampleUrl : ''
          const coverPage = data[idx].coverPage ? publicFileUrl + data[idx].coverPage : ''
          const colorRes = await getMaterialInfos({ count: false, materialName: data[idx].materialName })
          if (colorRes.code === 200) {
            const list = colorRes.result.list
            const colorList = list.length > 0 ? list[0].materialColorInfoVOS : []
            return {
              materialInfoId: data[idx].materialInfoId,
              materialName: data[idx].materialName,
              userPart: x.userPart,
              color: color,
              technology: data[idx].technology,
              technologyList: [data[idx].technology],
              coverPage: coverPage,
              caseImg: caseImg,
              colorList: colorList
            };
          }

        }) || [];
      tableData.value = await Promise.all(temp)
      console.log("暂无数据", tableData.value)
    } else {
      ElMessage({
        type: "warning",
        message: "暂无数据",
      });
    }
  }
  catch (error) {
    console.info("error", error)
  }
};

const formInline = reactive({
  building: [],
  // colorSys: "",
  // color: [],
  // grade: "",
});
const cascaderProps = {
  value: "buildingTypeInfoId",
  label: "buildingTypeName",
};
const buildingData = ref([]);
const colorSysOptions = ref([]);
const colorInfoOptions = ref([]);
const gradeInfoOptions = ref([]);
const getGradeListData = async () => {
  const params = {
    count: false,
    pageId: 1,
    pageSize: 20,
  };
  try {
    const res = await getGradeInfoSelectData(params);

    if (res.code == 200) {
      gradeInfoOptions.value = res.result.list || [];
    }
  } catch (error) { }
};
const changeColorSys = () => {
  getColorListData();
};
const getColorSysListData = async () => {
  const params = { count: true, pageId: 1, pageSize: 20 };
  try {
    const res = await getInfoSysSelectData();
    if (res.code == 200) {
      colorSysOptions.value = res.result || [];
    }
  } catch (error) { }
};
const getListData = async () => {
  const params = { count: true, pageId: 1, pageSize: 20 };
  try {
    const res = await allBuildingTypeInfo();
    // const res = await buildingTypeInfos(params);
    if (res.code == 200) {
      buildingData.value = res.result || [];
    }
  } catch (error) { }
};
const getColorListData = async () => {
  const params = {
    count: true,
    pageId: 1,
    pageSize: 20,
    colorSystemValue: formInline.colorSys,
  };
  try {
    const res = await getColorInfoSelectData(params);
    // const res = await buildingTypeInfos(params);
    if (res.code == 200) {
      colorInfoOptions.value = res.result.list || [];
    }
  } catch (error) { }
};
getListData();
getColorSysListData();
getColorListData();
getGradeListData();
</script>
<style lang="scss" scoped>
.color-badge {
  width: 30px;
  height: 10px;
}

.avatar-uploader {
  :deep .el-upload--picture-card {
    width: 100%;
    height: 100px;
  }
}

.report-wrap {
  // height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;

  .report-header {
    // height: 40px;
    display: flex;
    background: #fff;
    justify-content: space-between;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    padding: 10px 30px;
    margin: 0px 0;
    position: fixed;
    width: 100%;

    .el-page-header {
      width: auto;
      background: #fff;
      border-radius: 10px;
      padding-left: 20px;
      display: flex;
      align-items: center;

      :deep .el-page-header__breadcrumb {
        margin-bottom: 0;
      }

      .page-title {
        color: #999;
      }

      .page-content {
        display: flex;
        align-items: center;
      }
    }

    .right-header-content {
      display: flex;
      align-items: center;

      .el-avatar {
        margin-left: 10px;
      }

      .el-dropdown {
        margin-left: 10px;
      }
    }
  }

  .report-content {
    flex: 1;
    padding-top: 60px;

    .report-box {
      width: 1200px;
      margin: 0 auto;

      .report-ppt-item {
        width: 888px;
        height: 594px;
        background: #fff;
        border-radius: 20px;
        margin-top: 40px;
        margin: 40px auto;

        &.item-first {
          display: flex;
          flex-direction: column;
          justify-content: center;

          // align-items: center;
          img {
            width: 100%;
            flex: 1;
          }

          .item-first-bottom {
            height: 180px;
            padding: 20px;

            .first-item-title {
              font-size: 36px;
              font-weight: bold;
            }

            .item-date {
              margin-top: 20px;
            }
          }
        }

        &.item-second {
          .page-title {
            padding: 30px;
            text-align: right;
            font-size: 22px;
            font-weight: bold;
          }

          .brand-title {
            padding: 25px;
            text-align: left;
            padding-left: 100px;
            font-size: 36px;
            font-weight: bold;
            color: #cac226;
          }

          .ppt-title {
            padding: 20px;
            text-align: left;
            padding-left: 100px;
            font-size: 30px;
            font-weight: bold;
            color: #ba6b10;
          }

          .page-footer-title {
            padding: 30px;
            text-align: right;
            font-size: 26px;
            font-weight: bold;
            color: #cac226;
          }
        }

        &.item-third {
          .page-title {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px;
            font-weight: bold;
            color: #ba6b10;
          }
        }

        &.item-fifth {
          .page-title {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px;
            font-weight: bold;
            color: #ba6b10;
          }
        }

        &.item-sixth {
          .container {
            // width: 100%;
            padding: 20px 5px;
            margin: 5px;
            margin-top: 0;
            height: 515px;
            // padding-right: 200px;
            // box-sizing: border-box;
            border: 1px dashed #e0e0e0;
            position: relative;
            display: flex;

            .edit-btn {
              position: absolute;
              top: -10px;
              left: 250px;
              // display: none;
            }

            .operate-btn-wrap {
              width: 300px;
              // background: #fff;
              position: absolute;
              top: -10px;
              left: 250px;
              display: flex;
              justify-content: space-between;
            }

            &:hover {
              // .edit-btn {
              //   display: block;
              // }
            }

            .canvas-wrap {
              width: 420px;
              //width: 100%;
              height: 500px;
              display: flex;
              justify-content: center;
              align-items: center;
              margin: 5px;

              margin-top: 0;
              // border: 1px dashed #e0e0e0;
              // position: relative;
            }

            .table-wrap {
              width: calc(100% - 426px);
            }
          }

          .page-title {
            padding: 20px;
            text-align: left;
            padding-left: 50px;
            font-size: 22px;
            font-weight: bold;
            color: #ba6b10;
          }
        }

        &.item-seventh {
          display: flex;
          flex-direction: column;
          padding: 20px;

          .page-title {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px;
            font-weight: bold;
            color: #ba6b10;
          }

          .page-bottom-desc {
            border-top: 1px dashed #ba6b10;
            padding: 20px;
            height: 80px;
            color: #ba6b10;
          }
        }

        &.item-eighth {
          display: flex;
          flex-direction: column;
          padding: 20px;

          .page-header {
            display: flex;
            justify-content: space-between;
            padding: 20px 10px;
          }

          .page-title {
            flex: 1;

            font-size: 22px;
            font-weight: bold;
            color: #ba6b10;
          }
        }
      }
    }
  }
}

:deep .el-select-dropdown__item {
  padding: 5px
}

.el-select-dropdown__item {
  padding: 5px
}

:deep .inline-input {
  :deep .el-input {
    border: none;
  }

  .el-input__wrapper {
    box-shadow: none
  }

  .el-input__wrapper {
    box-shadow: none
  }
}
</style>
<style>
/* 抽屉从右向左 */
.AIdrawerWrapper {
  /* margin-left: auto; */
}

/* mask蒙版的宽度 */
.AIdrawer {
  width: 400px;
  right: 0;
  left: auto !important;
  /* top: 0 !important; */
}

/* 用important做样式穿透 */
.el-drawer {
  /* position: relative; */
  /* left: 100vw;
  margin-top: 87px;
  width: 19vw !important;
  height: 92% !important; */
}

.drawer-wrap {
  background: #fff;
  width: 400px;
  position: fixed;
  right: 0;
  height: 100vh;
  padding: 20px;
}
</style>
